#!/bin/bash

silent=
if [[ $1 == silent ]]; then
    silent="&>/dev/null"
fi

ex() {
    rm -f "test file" "temp file"
    exit ${1:-1}
}

cp test.001.in "test file"

./mark2html -i "test file" -o "temp file" &>/dev/null 
if ! diff -Nua "test.001.out" "temp file" &>/dev/null; then
    echo "Presentation error 1" >&2
    ex
fi

cat "test file" | ./mark2html -i - -o "temp file"
if ! diff -Nua "test.001.out" "temp file" &>/dev/null; then
    echo "Presentation error 2" >&2
    ex
fi

cat "test file" | ./mark2html -i - -o - > "temp file" 
if ! diff -Nua "test.001.out" "temp file" &>/dev/null; then
    echo "Presentation error 3" >&2
    ex
fi

cat "test file" | ./mark2html > "temp file" 
if ! diff -Nua "test.001.out" "temp file" &>/dev/null; then
    echo "Presentation error 4" >&2
    ex
fi

wa=0
for a in test.*.in
do
    eval ./mark2html -i "'$a'" -o "'temp file'" $silent
    if ! eval diff -Nua "'${a%.*}.out'" "'temp file'" $silent; then
        echo "Wrong answer, test \`$a'" >&2
        wa=1
    fi
done

rm -f "test file" "temp file"

if ! cat ./mark2html | grep getopt &>/dev/null; then
    echo "getopts command not found but MUST be used. See 'man bash'."
    ex
fi

testfiles=(testme.sh test.*.in test.*.out)
testfiles=${#testfiles[@]}
allfiles=(*)
allfiles=${#allfiles[@]}

(( allfiles == (testfiles + 2) )) && echo "It is not like this is error, but it is better to keep sed script inside main file"
(( allfiles > (testfiles + 2) )) && echo "Hello, Melnikov!" && ex

[[ $wa == 0 ]] && echo "Accepted"
